package com.xjscrm.common.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
import com.xjscrm.common.entity.TencentCosConfig;
import com.xjscrm.common.enums.TencentCosRegionEnum;
import com.xjscrm.common.exception.BusinessException;
import com.xjscrm.common.result.ResponseCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;


public class TencentCosFileUtil {


    private static Logger logger = LoggerFactory.getLogger(TencentCosFileUtil.class);

    public static String uploadMaterialFile(String uploadMaterialFileUrl) throws IOException {
        URL url = new URL(uploadMaterialFileUrl);
        InputStream inputStream = new BufferedInputStream(url.openStream());
        String idStr = IdWorker.getIdStr() + "." + FileUtil.extName(uploadMaterialFileUrl);
        String fileUrl = "";
        TencentCosConfig tencentCosConfig = new TencentCosConfig();
        tencentCosConfig.setAppId("1304033052");
        tencentCosConfig.setSecretId("AKIDqa7PSGp9E4ey3sSmqgGaeT4SbU8WeXBZ");
        tencentCosConfig.setSecretKey("B6mCNIyOYTDI8k6D4f1B7tTpzwe6JHzS");
        tencentCosConfig.setRegion("ap-shanghai");
        tencentCosConfig.setBucketName("xiejusucai-1304033052");
        COSClient cosClient = null;
        try {
            cosClient = createCOSClient(tencentCosConfig);
            ObjectMetadata objectMetadata = new ObjectMetadata();
            // 上传的流如果能够获取准确的流长度，则推荐一定填写 content-length
            // 如果确实没办法获取到，则下面这行可以省略，但同时高级接口也没办法使用分块上传了
            objectMetadata.setContentLength(inputStream.available());
            //objectMetadata.setContentType(contentType);
            PutObjectRequest putObjectRequest = new PutObjectRequest(tencentCosConfig.getBucketName(), idStr, inputStream, objectMetadata);

            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            if (putObjectResult != null) {
                TencentCosRegionEnum tencentCosRegionEnum = TencentCosRegionEnum.getValue(tencentCosConfig.getRegion());
                if (tencentCosRegionEnum != null) {
                    fileUrl = "https://" + tencentCosRegionEnum.getDomain().replace("<BucketName>", tencentCosConfig.getBucketName()) + "/" + idStr;
                }
            }

        } catch (Exception e) {
            logger.error("上传文件失败：error={}" + e.getMessage());
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "上传失败");
        } finally {
            if (cosClient != null) {
                cosClient.shutdown();
            }
        }
        return fileUrl;
    }

    public static String uploadMaterialFileV1(String uploadMaterialFileUrl) throws IOException {
        File tempFile = FileUtil.createTempFile();
        HttpUtil.downloadFile(uploadMaterialFileUrl, tempFile);
        InputStream inputStream = Files.newInputStream(tempFile.toPath());
        String idStr = IdWorker.getIdStr() + "." + FileUtil.extName(uploadMaterialFileUrl);
        String fileUrl = "";
        TencentCosConfig tencentCosConfig = new TencentCosConfig();
        tencentCosConfig.setAppId("1304033052");
        tencentCosConfig.setSecretId("AKIDqa7PSGp9E4ey3sSmqgGaeT4SbU8WeXBZ");
        tencentCosConfig.setSecretKey("B6mCNIyOYTDI8k6D4f1B7tTpzwe6JHzS");
        tencentCosConfig.setRegion("ap-shanghai");
        tencentCosConfig.setBucketName("xiejusucai-1304033052");
        COSClient cosClient = null;
        try {
            cosClient = createCOSClient(tencentCosConfig);
            ObjectMetadata objectMetadata = new ObjectMetadata();
            // 上传的流如果能够获取准确的流长度，则推荐一定填写 content-length
            // 如果确实没办法获取到，则下面这行可以省略，但同时高级接口也没办法使用分块上传了
            objectMetadata.setContentLength(inputStream.available());
            //objectMetadata.setContentType(contentType);
            PutObjectRequest putObjectRequest = new PutObjectRequest(tencentCosConfig.getBucketName(), idStr, inputStream, objectMetadata);

            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            if (putObjectResult != null) {
                TencentCosRegionEnum tencentCosRegionEnum = TencentCosRegionEnum.getValue(tencentCosConfig.getRegion());
                if (tencentCosRegionEnum != null) {
                    fileUrl = "https://" + tencentCosRegionEnum.getDomain().replace("<BucketName>", tencentCosConfig.getBucketName()) + "/" + idStr;
                }
            }

        } catch (Exception e) {
            logger.error("上传文件失败：error={}" + e.getMessage());
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "上传失败");
        } finally {
            if (cosClient != null) {
                cosClient.shutdown();
            }
            tempFile.delete();
        }
        return fileUrl;
    }


    public static COSClient createCOSClient(TencentCosConfig tencentCosConfig) {
        //1 初始化用户身份信息（secretId, secretKey）。
        COSCredentials cred = new BasicCOSCredentials(tencentCosConfig.getSecretId(), tencentCosConfig.getSecretKey());
        // 2 设置 bucket 的地域
        Region region = new Region(tencentCosConfig.getRegion());
        ClientConfig clientConfig = new ClientConfig(region);
        // 从 5.6.54 版本开始，默认使用了 https
        clientConfig.setHttpProtocol(HttpProtocol.https);
        // 3 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);

        // 生成 cos 客户端。
        return new COSClient(cred, clientConfig);
    }
}
